//
//  AddMeterViewController.swift
//  Employee
//
//  Created by tancheng on 2018/6/21.
//  Copyright © 2018年 remotevillage. All rights reserved.
//

import Foundation
import RxCocoa
import RxSwift
import Photos
import IQKeyboardManager
import SwiftyJSON

class AddMeterViewController: BaseVC {
    
    var isPublic = false //是否是公摊表

    //
    lazy var tableView: UITableView = {
       
        let tabV = UITableView(frame: CGRect.zero, style: .plain)
        tabV.tableFooterView = UIView(frame: CGRectMake(0, 0, UIScreen.width, 10))
        tabV.backgroundColor = GlobalConfig.pageColor
        tabV.dataSource = self
        tabV.delegate = self
        tabV.separatorStyle = .none
        tabV.register(UINib.init(nibName: "AddMeterMultipleSetsCell", bundle: nil), forCellReuseIdentifier: AddMeterMultipleSetsCell.reuseIdentifer)
        tabV.register(AddMeterTextParamCell.classForCoder(), forCellReuseIdentifier: AddMeterTextParamCell.reuseIdentifier)
        tabV.register(AddMeterImageParamCell.classForCoder(), forCellReuseIdentifier: AddMeterImageParamCell.reuseIdentifier)
        tabV.register(UINib.init(nibName: "AddMeterRemarkParamCell", bundle: nil), forCellReuseIdentifier: AddMeterRemarkParamCell.reuseIdentifer)

        
        return tabV
    }()
    
    var params: [AddMeterModel] = []
    var regionData:[RegionModel] = []
    var navItem: UIButton!
    
    lazy var submitBtn: UIButton = {
       let btn = UIButton(type: UIButtonType.custom)
        btn.backgroundColor = UIColor.blue
        btn.setTitle("保存", for: .normal)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.layer.cornerRadius = 5
        btn.layer.masksToBounds = true
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 17)
        btn.addTarget(self, action: #selector(submit), for: .touchUpInside)
        return btn
    }()
    
    private let disposeBag = DisposeBag()
    
    
    //
    let observer:Observable<AddMeterModel> = Observable.create { (obser) -> Disposable in
        
        for idx in 0...5 {
            var model = AddMeterModel()
            switch idx {
            case 0:
                model.name = ["仪表号","初始读数"]
                model.inputText = ["","0"]
                model.type = .multipleSets
                model.placeHolder = ["点击输入","点击输入"]
                
            case 1:
                model.name = ["归属类型"]
                model.type = .select
                model.inputId = ["",""]
                model.placeHolder = ["请选择"]
//            case 2:
//                model.name = ["表类型"]
//                model.type = .select
//                model.placeHolder = ["请选择"]
            case 2:
                model.name = ["房号"]
                model.type = .select
                model.placeHolder = ["请选择"]
            case 3:
                model.name = ["公摊区域"]
                model.type = .select
                model.placeHolder = ["请选择"]
            case 4:
                model.name = ["附件"]
                model.type = .image
                
            case 5:
                model.name = ["备注(选填)"]
                model.type = .multipleText
                model.placeHolder = ["点击输入"]
                model.textCount = 200
            default:
                model.name = [""]
                model.type = .number
                model.placeHolder = [""]
            }
            obser.onNext(model)
        }
        
        obser.onCompleted()
        
        return Disposables.create()
    }
    
    //
    override func viewDidLoad() {
        super.viewDidLoad()
        configData()
        setupUI()
        
        //NotificationCenter.default.rx.notification(Notification.Name)
        
        
    }
    //
    func setupUI() {
        title = "添加仪表"
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.bottom.equalToSuperview()
            make.right.left.equalToSuperview()
        }
        
        if #available(iOS 11, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        
        navItem = addNavRightItem()
        
        observerNavItem()
        
    }
    
    func addNavRightItem() -> UIButton {
        
        let btn = UIButton(type: .custom)
        btn.frame = CGRect.init(x: 0, y: 0, width: 54, height: 44)
        btn.setTitle("保存", for: .normal)
        btn.setTitleColor(UIColor.hex("#323C49", alpha: 0.2), for: .disabled)
        btn.setTitleColor(GlobalConfig.BGSkyBlueColor, for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        btn.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 11, bottom: 0, right: -11)
        btn.addTarget(self, action: #selector(submit), for: .touchUpInside)
        
        let item = UIBarButtonItem.init(customView: btn)
        navigationItem.rightBarButtonItem = item
        
        
        return btn
    }
    
    //
    func configData() {
    
        //监听
        observer.subscribe(onNext: {[weak self] (model) in
            if (self?.params.count)! < 7 {
                self?.params.append(model)
            }
            print(model)
            
        }, onError: nil, onCompleted: {
            print("22")
        }, onDisposed: nil).disposed(by: disposeBag)
       //
        getRegion()
        
    }
    
    //获取区域
    func getRegion() {
        let _ =  UserRequest.shared.getRegion(success: { (data) in
            self.regionData = data
        }) {
            
        }
    }
    
    //
    func observerNavItem() {
       
    }
    
    
    //MARK:提交数据
    @objc func submit() {
        view.endEditing(true)
       
        var assets:[PHAsset] = []
        
        var send = AddMeterSend()
        for model in params {
            if model.type == .image {
                assets = model.images
            }
            if model.type == .multipleSets {
                
                 let number = model.inputText[0].trimmingCharacters(in: .whitespacesAndNewlines)
                
                send.meterNumber = model.inputText[0]
                
                guard !number.isEmpty else {
                    showHint("请输入\(model.name[0])")
                    return
                }
                guard number.count <= 40 else {
                    showHint("仪表号不能超过40字")
                    return
                }
                //
                let read = model.inputText[1].trimmingCharacters(in: .whitespacesAndNewlines)
                
                
                
                //默认读数为0
                //send.firstRead = read.isEmpty ? "0" : read
                guard !read.isEmpty else {
                    showHint("请输入\(model.name[0])")
                    return
                }
                
                guard read.sj.isMeterRead else {
                    showHint("\(model.name[1])只能输入1位小数")
                    return
                }
                
                send.firstRead = read
                
            }
            
            switch model.name.first! {
               case "归属类型":
                    send.ascription = model.inputId[0]
                    send.type = model.inputId[1]
                    guard !send.ascription.isEmpty else {
                        showHint("请选择\(model.name[0])")
                        return
                    }
//                case "表类型":
//                    send.type = model.inputId.first ?? ""
//                    guard !send.type.isEmpty else {
//                        showHint("请选择\(model.name[0])")
//                        return
//                }
                case "房号":
                    send.houseId = model.inputId.first ?? ""
                    guard !send.houseId.isEmpty else {
                        showHint("请选择\(model.name[0])")
                        return
                }
                case "公摊区域":
                    send.regionId = model.inputId.first ?? ""
                    if isPublic {
                        guard !send.regionId.isEmpty else {
                            showHint("请选择\(model.name[0])")
                            return
                    }
                    
                
                }
                case "备注(选填)":
                    send.remark = model.inputText.first ?? ""
                    guard send.remark.count <= 200 else {
                        showHint("备注不能超过200字")
                        return
                }
                default:
                    break
            }
        
        }
        
        print("send",send)
    
        SJApp.showHUD(in: view)
        //showHud(in: view, hint: "正在上传...")
        
        //已经通过请求，不允许再次点击
        navItem.isEnabled = false
        
        guard assets.count > 0 else {
            
            MeterRequest.shared.addMeter(send: send, success: { [weak self] in
                
                runOnMainThread {
                    SJApp.hideHUD(in: self?.view ?? SJApp.keyWindow)
                    SJApp.hideStateBarHUD()
                    self?.showHint("添加成功")
                }
                
                
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1.5, execute: {
                    self?.navigationController?.popViewController(animated: true)
                })
                
            }, failure: { [weak self] in
                runOnMainThread {
                    SJApp.hideHUD(in: self?.view ?? SJApp.keyWindow)
                    SJApp.hideStateBarHUD()
                   // self?.showHint("该仪表已经添加到这套房下了，请不要重复添加")
                    self?.navItem.isEnabled = true
                }
               
            })
            
            return
        }
        
        runInBackground {
            var tempDatas: [Data] = []
            let uploadImages = PhotoHelper.fetchOriginalPhotos(with: assets)
            
            for uploadImage in uploadImages {
                tempDatas.append(uploadImage.uploadData)
            }
            
            let _ = FileRequest.shared.uploadImages(datas: tempDatas, progressClosure: { (progress) in
            }) { (ids) in
                
                var imageIds = ""
                
                for item in ids {
                   imageIds += item.fileId + ","
                }
                imageIds.removeLast()
                send.imageIds = imageIds
                 print("send",send)
                MeterRequest.shared.addMeter(send: send, success: { [weak self] in
                    
                    runOnMainThread {
                        SJApp.hideHUD(in: self?.view ?? SJApp.keyWindow)
                        SJApp.hideStateBarHUD()
                        self?.showHint("添加成功")
                    }
                    
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1.5, execute: {
                        self?.navigationController?.popViewController(animated: true)
                    })
                    
                    }, failure: { [weak self] in
                        runOnMainThread {
                            SJApp.hideHUD(in: self?.view ?? SJApp.keyWindow)
                            SJApp.hideStateBarHUD()
                            //self?.showHint("该仪表已经添加到这套房下了，请不要重复添加")
                            self?.navItem.isEnabled = true
                        }
                })
                
            }
        }
        
        
    }

}

extension AddMeterViewController: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return params.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let model = params[indexPath.row]
        
        if model.type == .image {
            
            return AddMeterImageParamCell.height
        }
        
        if model.type == .multipleText {
            return 124 + 20
        }
        if model.type == .multipleSets {
            return 208 + 20
        }
        
        if indexPath.row == 3 {
            return isPublic ? 70 : 0
        }
        
        return 70
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let model = params[indexPath.row]
        
        if model.type == .multipleSets {
            let cell = tableView.dequeueReusableCell(withIdentifier: AddMeterMultipleSetsCell.reuseIdentifer, for: indexPath) as! AddMeterMultipleSetsCell
            
            cell.paramModel = params[indexPath.row]
            
            cell.updateBlock = {[weak self] (text,idx) in
                self?.params[indexPath.row].inputText[idx] = text
                self?.observerNavItem()
            }
            
            return cell
        }
        
        if model.type == .image {
            let cell = tableView.dequeueReusableCell(withIdentifier: AddMeterImageParamCell.reuseIdentifier, for: indexPath) as! AddMeterImageParamCell
            cell.targetVC = self
            cell.paramModel = params[indexPath.row]
            cell.addImgBlock = {[weak self] imgs in
                self?.params[indexPath.row].images = imgs
            }
            cell.deleteImgBlock = {[weak self] index in
                self?.params[indexPath.row].images.remove(at: index)
            }
            return cell
        }
        
        if model.type == .multipleText {
            let cell = tableView.dequeueReusableCell(withIdentifier: AddMeterRemarkParamCell.reuseIdentifer, for: indexPath) as! AddMeterRemarkParamCell
            cell.beginEidtingBlock = {[weak self] in
                
                 self?.tableView.scrollToRow(at: IndexPath.init(row: (self?.params.count ?? 5) - 1, section: 0), at: .middle, animated: true)
                
                UIView.animate(withDuration: 0.25, delay: 0, options: UIViewAnimationOptions.init(rawValue: 7), animations: {
                    self?.tableView.snp.updateConstraints({ (make) in
                        make.top.equalToSuperview().offset(-250)
                        make.bottom.equalToSuperview().offset(-250)
                    })
                    self?.view.layoutIfNeeded()
                }, completion: nil)
                
               
               
            }
            
            cell.didEidtedBlock = {[weak self] text in
                
                UIView.animate(withDuration: 0.25, delay: 0, options: UIViewAnimationOptions.init(rawValue: 7), animations: {
                    self?.tableView.snp.updateConstraints({ (make) in
                        make.top.equalToSuperview().offset(0)
                        make.bottom.equalToSuperview().offset(0)
                    })
                    self?.view.layoutIfNeeded()
                }, completion: nil)
                
                self?.params[indexPath.row].inputText[0] = text
                self?.observerNavItem()//
            }
            cell.paramModel = params[indexPath.row]
            return cell
        }
        
       let cell = tableView.dequeueReusableCell(withIdentifier: AddMeterTextParamCell.reuseIdentifier, for: indexPath) as! AddMeterTextParamCell
        cell.paramModel = params[indexPath.row]
        
        return cell
        
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        cell.selectionStyle = .none
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        view.endEditing(true)
        selectInfo(idx: indexPath.row)
    }
    ///选择信息
    func selectInfo(idx:Int) {
        let model = params[idx]
        switch model.name.first! {
        case "归属类型":
            
            let treePicker = SJTreePicker()
            treePicker.style = .rule
            treePicker.title = "归属类型"
            
            let data = [
                ["orgId":"ordinary",
                 "orgName":"普通表",
                 "staffs":[
                    [
                        "staffId":"electricMeter",
                        "staffName":"电表",
                        ],
                    [
                        "staffId":"waterMeter",
                        "staffName":"水表",
                        ],
                    [
                        "staffId":"gasMeter",
                        "staffName":"燃气表",
                        ],
                    ]
                 ],
                
                ["orgId":"publicd",
                 "orgName":"公摊表",
                 "staffs":[
                    [
                        "staffId":"electricMeter",
                        "staffName":"电表",
                        ],
                    [
                        "staffId":"waterMeter",
                        "staffName":"水表",
                        ],
                    ]
                ]
                       ]
            
        
            treePicker.departments = Department.array(from: JSON(data).arrayValue)
            //let prioritys = Priority.array(from: [("ordinary", "普通表"), ("publicd", "公摊表")])
            //treePicker.prioritys = prioritys
            treePicker.show(in: self.navigationController!.view)
            
            treePicker.didSelectClosure = {[weak self] one,two in
                
                guard !one.1.isEmpty || !two.1.isEmpty else {return}
                
                self?.params[idx].inputText[0] = one.1 + "-" + two.1
                self?.params[idx].inputId[0] = one.0
                 self?.params[idx].inputId[1] = two.0
                self?.isPublic = one.0 == "publicd"
                self?.tableView.reloadRows(at: [IndexPath.init(row: idx, section: 0),IndexPath.init(row: 4, section: 0)], with: .automatic)
                self?.observerNavItem()
            }
        
            
//        case "表类型":
//            let treePicker = SJTreePicker()
//            treePicker.style = .priority
//            treePicker.title = "选择表类型"
//            let prioritys = Priority.array(from: [("electricMeter", "电表"), ("waterMeter", "水表"), ("gasMeter", "燃气表")])
//            treePicker.prioritys = prioritys
//            treePicker.show(in: self.navigationController!.view)
//
//            treePicker.didSelectClosure = {[weak self] one, _ in
//                self?.params[idx].inputText[0] = one.1
//                self?.params[idx].inputId[0] = one.0
//                self?.tableView.reloadRows(at: [IndexPath.init(row: idx, section: 0)], with: .automatic)
//                self?.observerNavItem()
//            }
        
            
        case "房号":
            let housePicker = TCActionPicker(regionData)
            //housePicker.isSelectHouse = true
            housePicker.show(in: SJApp.keyWindow)
            housePicker.selectBlock = {[weak self] (name,id) in
                if id.isEmpty {return}
                self?.params[idx].inputText[0] = name
                self?.params[idx].inputId[0] = id
                self?.tableView.reloadRows(at: [IndexPath.init(row: idx, section: 0)], with: .automatic)
                self?.observerNavItem()
            }
            
        case "公摊区域":
            let treePicker = SJTreePicker()
            treePicker.style = .priority
            treePicker.title = "公摊区域"
        
            let prioritys = Priority.array(from: regionData.map({($0.id,$0.name)}))
            treePicker.prioritys = prioritys
            treePicker.show(in: self.navigationController!.view)
            treePicker.didSelectClosure = {[weak self] one,two in
                
                self?.params[idx].inputText[0] = one.1
                self?.params[idx].inputId[0] = one.0
                self?.tableView.reloadRows(at: [IndexPath.init(row: idx, section: 0)], with: .automatic)
                self?.observerNavItem()
                
                
            }
        default:
            return
        }
    }
}



